<?php
class Helper_Cart{
    static $ship=array('email'=>'','gender'=>'', 'firstname'=>'','lastname'=>'','company'=>'', 'street1'=>'','street2'=>'', 'phone'=>'', 'postalcode'=>'', 'country'=>'','cityname'=>'','stateorprovince'=>'');
    function __construct(){
        $this->store=Q::INI('store');
    }
    /******
     *  goods[goods_id]=array(goods_id,quantity,weight,price,currency),
     *  ship=array(
     *  
     *          )     
     *  amount=     
     *  shipment=
     *  payment=
     *  status=               
     *  customer_id=
     */              
    static function cart($k=null,$v=null){
        if(isset($_SESSION['cart'][$k])){
            do{
                if(is_null($v)){ break;}
                // 校验 
                switch($k){
                    case 'currency':
                        $currency=Store_Currencies::used(Q::ini('store/store_id'),$v);
                        return $_SESSION['cart'][$k]=$currency->code;
                    break 1;
                }
                return $_SESSION['cart'][$k]=$v;
            }while(0);
            return $_SESSION['cart'][$k];
        }else{
            if(!isset($_SESSION['cart'])){
                self::destroy();
            }
            return $_SESSION['cart'];
        }
    }
    /**
     * 初始化
     */         
    static function destroy(){
        $_SESSION['cart']=null;
        $_SESSION['cart']=array(
            'goods'=>array(),
            'ship'=>self::$ship,
            'currency'=>Q::ini('store/currency'),
            'amount'=>0,
            'shipment'=>'',
            'payment'=>'',
            'coupon'=>'',
            'status'=>0,
            'customer_id'=>0,
        );
    }
    
    static function recalculate(){
//         $goods=Goods::find('goods_id in (?)',array_keys($_SESSION['cart']['goods']))->getAll();
        $a=0;
        if(isset($_SESSION['cart']['goods']) && count($_SESSION['cart']['goods'])){ 
            foreach($_SESSION['cart']['goods'] as $g){
              $t=$g['quantity']*$g['price'];
              $a+=Helper_Currency::conver($t,$g['currency']);
            }
        }else{
            $_SESSION['cart']['goods']=array();
        }
        $_SESSION['cart']['amount']=$a;
    }
    
    static function buildOrder($order_fields_array=null){
        $store=Q::INI('store');
        $order_id=Helper_Util::build_order_id();
        $amount=0;
        $shipping_cost_amount=0;
        if(isset($_SESSION['cart']['customer_id'])){
            $customer_id=$_SESSION['cart']['customer_id'];
        }
        foreach($_SESSION['cart']['goods'] as $g){
            //计算运费 ,这里 加上  货币 转换 
            $weight=$g['weight'] * $g['quantity'];
            $shipping_cost=Store_Shipment::calculate($_SESSION['cart']['ship']['country'],$_SESSION['cart']['shipment'],$weight);
            $shipping_cost_amount+=Helper_Currency::conver($shipping_cost);
            $t=Helper_Currency::conver($g['quantity']*$g['price'],$g['currency']);
            $amount+=$t;
            $goods_id=self::gidfromcartkey($g['goods_id']);
            $t=new Transaction;
            $t->changeProps(array(
               'store_id'=>$store['store_id'],
               'seller_id'=>$store['seller_id'],
               'customer_id'=>$customer_id,
               'order_id'=>$order_id,
               'goods_id'=>$goods_id,
               'quantity'=>$g['quantity'],
               'price'=>$g['price'],
               'shipping_cost'=>$shipping_cost,
               'title'=>$g['title'],
               'property_id'=>self::propstr($g['props']),
               'currency'=> Helper_Currency::using(),
               'status_payment'=>'wait',
            ));
            $t->save();
        }
        // 运费 
        $finel_amount=$shipping_cost_amount+$amount;
        $order=new Orders;
        $order_field=array(
             'store_id'=>$store['store_id'],
             'seller_id'=>$store['seller_id'],
             'customer_id'=>$customer_id,
             'order_id'=>$order_id,
             'ship_gender'=>$_SESSION['cart']['ship']['gender'],
             'ship_firstname'=>$_SESSION['cart']['ship']['firstname'],
             'ship_lastname'=>$_SESSION['cart']['ship']['lastname'],
             'ship_company'=>$_SESSION['cart']['ship']['company'],
             'ship_cityname'=>$_SESSION['cart']['ship']['cityname'],
             'ship_stateorprovince'=>$_SESSION['cart']['ship']['stateorprovince'],
             'ship_country'=>$_SESSION['cart']['ship']['country'],
//              'ship_countryname'=>$_SESSION['cart']['ship']['countryname'],
             'ship_street1'=>$_SESSION['cart']['ship']['street1'],
             'ship_street2'=>$_SESSION['cart']['ship']['street2'],
             'ship_postalcode'=>$_SESSION['cart']['ship']['postalcode'],
             'ship_phone'=>$_SESSION['cart']['ship']['phone'],
             'ship_email'=>$_SESSION['cart']['ship']['email'],
             'total_amount'=>$amount,
             'finel_amount'=>$finel_amount,
             'shipping_cost'=>$shipping_cost_amount,
             'finalvaluefee'=>0,
             'discount'=>0,
             'tax_cost'=>0,
             'payment_id'=>$_SESSION['cart']['payment'],
             'shipment_id'=>$_SESSION['cart']['shipment'],
             'status_payment'=>'wait',
             'currency'=> Helper_Currency::using(),
        );
        if(count($order_fields_array)){
            if(isset($order_fields_array['memo'])){
                $order_field['memo']=$order_fields_array['memo'];
            }
        }
        $order->changeProps($order_field);
        $order->save();
        // notification 创建订单 .
        $notification=new cmshopapi_Notification();
        $notification->OrderCreated($order,Q::ini('store/store_id'));
        if(!$customer_id){
            self::orderAdd($order_id);
        }
        if($order->isNewRecord()){
            return null;
        }
        return $order;
    }
    /**
     * Check coupon  
     *  ABCDEF123     
     */         
    function coupon($coupon=''){
        // check
        if(preg_match('/^[A-Za-z]{6}[0-9]{3}$/',$coupon)){
            self::cart('coupon',$coupon);
            return true;
        }else{
            return false;
        }
    }
    
    static function fromstore(){
        return self::cart();
    }
    
    static function status(){
        return self::cart('status');
    }
    
    static function goodscount(){
        if(self::cart('status')){
            return count(self::cart('goods'));
        }
        return 0;
    }
    
    
//     static function ordercount(){
//         if(isset($_SESSION['order'])){
//             return count($_SESSION['order']);
//         }else{
//             return 0;
//         }
//     }
//     
//     static function orderAdd($order_id){
//         $_SESSION['order'][$order_id]=$order_id;
//     }
//     
//     static function orders(){
//         return $_SESSION['order'];
//     }

    static function ordercount(){
        if(isset($_COOKIE['order'])){
            return count($_COOKIE['order']);
        }else{
            return 0;
        }
    }
    
    /***
     *  Add or remove
     */         
    static function orderAdd($order_id,$do='add'){
        //if(isset($_COOKIE['order'])){
        //    $_COOKIE['order'][$order_id]=$order_id;
        //}
        if($do=='remove'){
            $t=time()-3600;
        }else{
            $t=time()+108000;
        }
        setcookie('order['.$order_id.']',$order_id,$t,'/'); //31536000
    }
    
    static function orders(){
        return $_COOKIE['order'];
    }
    
    static function gidfromcartkey($cartkey){
        list($goods_id)=explode('_',$cartkey);
        return $goods_id;
    }
    
    static function propstr($ps,$iskey=1){
        if(is_array($ps)&&count($ps)){
            if($iskey){
                return '_'.implode('|',$ps);
            }else{
                return implode('|',$ps);
            }
        }else{
            return '';
        }
    }
    /**
     * 独立的 运费计算  函数 
     */         
    static function shipcost_calculate($country=null){
        if(is_null($country)&&strlen($_SESSION['cart']['ship']['country'])){
            $country=$_SESSION['cart']['ship']['country'];
        }
        $shipping_cost_amount=array();
        if(count($_SESSION['cart']['goods'])){ foreach($_SESSION['cart']['goods'] as $g){
            $weight=$g['weight'] * $g['quantity'];
            $shipping_cost=Store_Shipment::calculate($country,null,$weight);
            if(is_array($shipping_cost)){
                foreach($shipping_cost as $k=>$shipping_cost_v){
                    $shipping_cost[$k]=Helper_Currency::conver($shipping_cost_v);
                    if(isset($shipping_cost_amount[$k])){
                        $shipping_cost_amount[$k]+=$shipping_cost[$k];
                    }else{
                        $shipping_cost_amount[$k]=$shipping_cost[$k];
                    }
                }
            }
        }}
        return $shipping_cost_amount;
    }
}